package com.xesj.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xesj.model.User;
import com.xesj.service.UserServiceI;
import com.xesj.util.PageData;

@Controller
@RequestMapping("registController")
public class RegistMember extends BaseController {
	
	@Autowired
	private UserServiceI userService;
	@RequestMapping("/goRegistPage")
	public ModelAndView goRegistPage(){
		ModelAndView mv = this.getModelAndView();
		PageData pd=new PageData();
		mv.setViewName("main/registMember");	
		return mv;		
	}
	
	 @RequestMapping("/registMember")	 
	 public ModelAndView regist( User user,HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IllegalStateException, IOException{
		 ModelAndView mv = this.getModelAndView();
		 PageData pd=new PageData();
		 if (!file.isEmpty()) {
			 //上传路径
			 String realPath = request.getSession().getServletContext().getRealPath("/upload");
			 //上传文件名
			 String originalFilename = file.getOriginalFilename();
			 SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
			 String filename = sdf.format(new Date())+originalFilename;
			 user.setHeadpic(filename);
			 File filepath = new File(realPath, filename);
			 if (!filepath.exists()) {
				 filepath.getParentFile().mkdirs();
			}
			 //上传
			 file.transferTo(new File(realPath+File.separator+filename));
		}else {
			pd.put("success", false);
			pd.put("msg", "文件上传有误");
			mv.addObject("pd", pd);
			mv.setViewName("main/registMember");
			return mv;
		}
		 
		 
		 int count= userService.registMember(user);
		 if (count!=0) {
			 pd.put("success", true);
			 pd.put("msg", "注册成功");
			 mv.setViewName("main/index");
		}else {
			pd.put("success", false);
			pd.put("msg", "注册失败");
			mv.setViewName("main/registMember");
		}
		 mv.addObject("pd", pd);
		
		return mv;
		 
	 }
	
	
	
}
